package com.itbaizhan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/*设置字节型响应
常见的字节型响应：
resp.setContentType("image/jpeg")
设置响应类型为图片类型，图片类型为jpeg或jpg格式。

resp.setContentType("image/gif")
设置响应类型为图片类型，图片类型为gif格式。
*/
/*字节响应类型
* 以字节形式读到数组中，再设置响应类型，在输出流对象输出*/
public class ResponseByteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //给定读取响应图片的路径
        File file = new File("e:/picture/1002.jpg");
        //创建读取图片的IO流
        InputStream is = new FileInputStream(file);
        //图片的缓存区   is.available()返回图片大小的长度
        byte[] buff = new byte[is.available()];
        //将字节读到缓存中
        is.read(buff);

        //设置响应类型
        resp.setContentType("image/jpeg");
        //获取字节输出流对象
        OutputStream os = resp.getOutputStream();
        //将字节写出
        os.write(buff);
        os.flush();
        os.close();
    }
}
